<?php
namespace common\components\actions;

use yii\base\Action;
use yii\web\BadRequestHttpException;
use yii\helpers\ArrayHelper;
use common\components\helpers\Fun;
use yii\web\HttpException;
use yii\web\ServerErrorHttpException;

/**
 * 后台通用删除Action
 * @author: 郭建飞
 * Date: 2015-3-11
 * Time: 11:11
 */


class DeleteAction extends Action{

    /**
     * @var string $param 删除记录时传递参数用的key
     */
    public $param='id';

    /**
     * @var string $modelClass 删除记录所对应的模型名称
     */
    public $modelClass;

    /**
     * @var array $message 删除操作执行后提示的结果信息
     */
    public $message=['success'=>'删除成功'];

    /**
     * @var string $redirectTo 删除后跳转到哪个控制器地址
     */
    public $redirectTo;

    /**
     * @var array $isHasChild 判断是否删除当前记录是否存在子记录
     */
    public $isHasChild=[];

    /**
     * @var array $redirectParam 删除后跳转到控制附带的参数
     */
    public $redirectParam=[];

    /**
     * @var array $checkParam 删除绑定参数
     */
    public $checkParam;


    /**
     * 默认Action执行方法，重写父类方法
     */
    public function run(){
        if(!empty($this->checkParam)&&\Yii::$app->request->get($this->checkParam)==null){
            throw new BadRequestHttpException ( \Yii::t('backend','非法请求'),400);
        }
        $pk = \Yii::$app ->request->get($this->param);
        if (empty ( $pk )){
            throw new BadRequestHttpException ( \Yii::t('backend','信息不存在'),404);
        }
        $model_name=$this->modelClass;
        $model = $model_name::findOne((int)$pk);
        if (! $model){
            throw new BadRequestHttpException (\Yii::t('backend','信息不存在') , 404 );
        }
        $url=!empty($this->redirectParam)?Fun::Url(ArrayHelper::merge([$this->redirectTo],$this->redirectParam)):Fun::Url([$this->redirectTo]);
        if(!empty($this->isHasChild)){
            $child_model_name=$this->isHasChild['ChildModelClass'];
            $child_count=$child_model_name::find()->where([$this->isHasChild['ChildModelField']=>(int)$pk])->count();
            if($child_count>0){
                return $this->controller->redirectMessage($this->message['warning_child'], $url,true);
            }
        }

        if ($model->delete ()){
            return $this->controller->redirectMessage($this->message['success'], $url,true);
        }
        throw new ServerErrorHttpException ( 500 ,'系统错误');

    }
}